package cn.mengfly.fxtest.app;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.TilePane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class TileApp extends Application {



    @Override
    public void start(Stage primaryStage) {
        TilePane tilePane = new TilePane();
        tilePane.setPrefColumns(2);
        tilePane.setPrefRows(2);
        tilePane.setAlignment(Pos.CENTER);

        Circle redCircle = new Circle(50, Color.RED);
        Circle greenCircle = new Circle(50, Color.GREEN);
        Circle yellowCircle = new Circle(50, Color.YELLOW);
        Circle blueCircle = new Circle(50, Color.BLUE);

        List<Circle> circles = new ArrayList<>();
        circles.add(redCircle);
        circles.add(greenCircle);
        circles.add(yellowCircle);
        circles.add(blueCircle);

        circles.forEach(circle -> {
            circle.getProperties().put("selected", Boolean.FALSE);
        });
        tilePane.getChildren().addAll(circles);

        tilePane.setOnMouseClicked(
                event -> tilePane.getChildren()
                        .stream()
                        .filter(node -> node.contains(node.sceneToLocal(event.getSceneX(), event.getSceneY(), true)))
                        .findFirst().ifPresent(node -> {
                    Boolean isSelected = (Boolean) node.getProperties().get("selected");
                    if (isSelected == null || isSelected.equals(Boolean.FALSE)) {
                        node.setOpacity(0.3d);
                        node.getProperties().put("selected", Boolean.TRUE);
                    } else {
                        node.setOpacity(1.0);
                        node.getProperties().put("selected", Boolean.FALSE);
                    }
                })
        );

        Scene scene = new Scene(tilePane);
        scene.setOnKeyPressed(event -> {
            if (event.getCode().equals(KeyCode.S)) {
                Collections.shuffle(circles);
                tilePane.getChildren().clear();
                tilePane.getChildren().addAll(circles);
            }
        });

        primaryStage.setScene(scene);
        primaryStage.setTitle("Tile App");
        primaryStage.show();
    }
}
